package com.igeek.boot.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import com.igeek.boot.result.Result;
import com.igeek.boot.utils.JwtHelper;
import com.igeek.boot.utils.WebUtils;
import org.springframework.stereotype.Component;

import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器
 *
 * @author chemin
 * @since 2024/1/2
 */
//@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求中判断是否携带请求头
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            WebUtils.renderString(response , JSONUtil.toJsonStr(new Result(false , "当前token不存在" , 403)));
            return false;
        }

        //2.请求头中是否携带了争取的token信息
        Integer userId = JwtHelper.getUserId(token);
        if(userId==null){
            WebUtils.renderString(response , JSONUtil.toJsonStr(new Result(false , "用户信息过期，请重新登录" , 403)));
            return false;
        }

        //3.请求域设置会员ID
        request.setAttribute("userId" , userId);
        return true;
    }
}
